package com.yuyou.fn.tradingservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.wens.framework.service.impl.SuperServiceImpl;
import com.github.wens.mybatisplus.examples.Example;
import com.github.wens.mybatisplus.plugins.Page;
import com.yuyou.fn.common.exception.BusException;
import com.yuyou.fn.common.service.ISmsService;
import com.yuyou.fn.common.util.BeanUtils;
import com.yuyou.fn.common.util.TimeUtils;
import com.yuyou.fn.common.util.Utils;
import com.yuyou.fn.educational.entity.SummerWinterDate;
import com.yuyou.fn.platform.entity.SysUser;
import com.yuyou.fn.settlement.entity.MainAccount;
import com.yuyou.fn.settlement.service.IMainAccountService;
import com.yuyou.fn.settlement.service.ISettlementService;
import com.yuyou.fn.tradingservice.entity.*;
import com.yuyou.fn.tradingservice.mapper.ServiceOrderItemMapper;
import com.yuyou.fn.tradingservice.service.*;
import com.yuyou.fn.tradingservice.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 *
 * ServiceOrderItem 表数据服务层接口实现类
 *
 */
@Service
public class ServiceOrderItemServiceImpl extends SuperServiceImpl<ServiceOrderItemMapper, ServiceOrderItem,Long> implements IServiceOrderItemService {

    @Resource
    private IServiceOrderService orderService;

    @Resource
    private IPersonLeaseMessageService personLeaseMessageService;

    @Resource
    private IServiceProductService serviceProductService;


    @Resource
    private IServiceOrderService serviceOrderService;

    @Resource
    private ISmsService smsService;

    @Resource
    private IServiceCategoryService serviceCategoryService;

    @Resource
    private ISettlementService settlementService;

    @Resource
    private IMainAccountService mainAccountService;



    @Override
    public List<ServiceOrderItem> findByLessCreateTimeAndStatus(Date date, Integer chargingStatus) {
        Example<ServiceOrderItem> example= ServiceOrderItem.createExample();
        // example.selectProperties("classId");
        Example.Criteria criteria=example.createCriteria();
        criteria.andEqualTo("chargingStatus",chargingStatus);
        criteria.andLessThan("createTime",date);
        List<ServiceOrderItem> serviceOrderItemList =this.findListByExample(example);
        return serviceOrderItemList;
    }

    @Override
    public List<ServiceOrderItem> findByLessRefundTimeAndStatus(Date date, Integer chargingStatus) {
        Example<ServiceOrderItem> example= ServiceOrderItem.createExample();
        // example.selectProperties("classId");
        Example.Criteria criteria=example.createCriteria();
        criteria.andEqualTo("chargingStatus",chargingStatus);
        criteria.andLessThan("refundTime",date);
        List<ServiceOrderItem> serviceOrderItemList =this.findListByExample(example);
        return serviceOrderItemList;
    }

    @Override
    public List<ServiceOrderItem> findByLessUpdateTimeAndGoodState(Date date, Integer goodState) {
        Example<ServiceOrderItem> example = ServiceOrderItem.createExample();
        // example.selectProperties("classId");
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("goodState", goodState);
        criteria.andLessThan("updateTime", date);
        List<ServiceOrderItem> serviceOrderItemList = this.findListByExample(example);
        return serviceOrderItemList;
    }

    @Override
    public List<ServiceOrderItem> findByOrderIdAndChargingStatus(Long orderId, Integer chargingStatus) {
        Example<ServiceOrderItem> example= ServiceOrderItem.createExample();
        Example.Criteria criteria=example.createCriteria();
        criteria.andEqualTo("orderId",orderId);
        criteria.andEqualTo("chargingStatus",chargingStatus);
        List<ServiceOrderItem> serviceOrderItemList =this.findListByExample(example);
        return serviceOrderItemList;
    }

    @Override
    @Transactional
    public void cancelServiceOrderItem(Long orderItemId, Integer orderStatus) {
        ServiceOrderItem serviceOrderItem=this.findById(orderItemId);
        ServiceOrderItem changeServiceOrderItem=new ServiceOrderItem();
        changeServiceOrderItem.setOrderStatus(orderStatus);
        changeServiceOrderItem.setOrderItemId(orderItemId);
        this.updateSelectiveById(changeServiceOrderItem);
        ServiceOrder serviceOrder=serviceOrderService.findById(serviceOrderItem.getOrderId());
        BigDecimal paidAmount=serviceOrder.getPayableAmount().subtract(serviceOrderItem.getPayableAmount());
        serviceOrderService.changePayableAmount(serviceOrderItem.getOrderId(),paidAmount);

        if (serviceOrderItem.getType()==0){
            ServiceProduct serviceProduct=serviceProductService.findById(serviceOrderItem.getProductId());
            if (serviceProduct!=null){
                Integer inventory=serviceProduct.getInventory()+serviceOrderItem.getQuantity();
                ServiceProduct update=new ServiceProduct();
                update.setInventory(inventory);
                update.setProductId(serviceProduct.getProductId());
                update.setUpdateTime(TimeUtils.now());
                serviceProductService.updateSelectiveById(update);
            }

        }

        if (StringUtils.isNotEmpty(serviceOrderItem.getPersonLeaseIds())){
            List<Long> personLeaseIds= Utils.toLongIds(serviceOrderItem.getPersonLeaseIds());
            if (personLeaseIds.size()>0){
                personLeaseMessageService.changeLeaseStateByIds(personLeaseIds,4);
            }

        }
    }

    @Override
    public void applyRefund(Long orderItemId, SysUser user, Integer chargingStatus,String refundReasonTag,String refundReason) {
        Example<ServiceOrderItem> example=ServiceOrderItem.createExample();
        Example.Criteria criteria=example.createCriteria();
        criteria.andEqualTo("buyerId",user.getUserId());
        criteria.andEqualTo("orderItemId",orderItemId);
        ServiceOrderItem serviceOrderItem=this.findOneByExample(example);
        if (serviceOrderItem==null) {
            throw new BusException("查不到该订单信息，申请退款失败");
        }
        if(serviceOrderItem.getChargingStatus()!=2){
            throw new BusException("该订单尚未付款成功，申请退款失败");
        }
        if(serviceOrderItem.getType()==2){
            String personLeaseMessageIds=serviceOrderItem.getPersonLeaseIds();
            List<Long> personLeaseMessageIdList=Utils.toLongIds(personLeaseMessageIds);
            List<PersonLeaseMessage> personLeaseMessageList=personLeaseMessageService.findByIds(personLeaseMessageIdList);
            //List<Date>
            // throw new BusException("该订单尚未付款成功，申请退款失败");
            Date minStartDate=null;
            String minStartTime=null;
            for (PersonLeaseMessage personLeaseMessage:personLeaseMessageList){
                if (minStartDate==null){
                    minStartDate=personLeaseMessage.getStart();
                    minStartTime=personLeaseMessage.getStartTime();
                    continue;
                }
                if (minStartDate.before(personLeaseMessage.getStart())){
                    minStartDate=personLeaseMessage.getStart();
                    minStartTime=personLeaseMessage.getStartTime();
                }else if (minStartDate.equals(personLeaseMessage.getStart())&& minStartTime.compareTo(personLeaseMessage.getStartTime())>0){
                    minStartTime=personLeaseMessage.getStartTime();
                }
            }
            String start=Utils.formatDate(minStartDate,"yyyy-MM-dd")+" "+minStartTime;
            Date startDate=Utils.parseDate(start,"yyyy-MM-dd HH:mm");
            //TimeUtils.hoursOfTwo(startDate,TimeUtils.now());
            Long hour=(startDate.getTime()- TimeUtils.now().getTime())/(60*60*1000);
            if (hour<24){
                throw new BusException("当前时间与最小租赁时间相差小于24小时，不可申请退款");
            }
        }



        ServiceOrderItem serviceOrderItemVo=new ServiceOrderItem();
        serviceOrderItemVo.setOrderItemId(orderItemId);
        serviceOrderItemVo.setChargingStatus(chargingStatus);
        serviceOrderItemVo.setUpdateTime(TimeUtils.now());
        serviceOrderItemVo.setRefundTime(TimeUtils.now());
        serviceOrderItemVo.setOrderStatus(chargingStatus);
        serviceOrderItemVo.setRefundReason(refundReason);
        serviceOrderItemVo.setRefundReasonTag(refundReasonTag);
        this.updateSelectiveById(serviceOrderItemVo);
        try{
            smsService.send(Arrays.asList(serviceOrderItem.getSellerPhoneNo()),"您好，您在“誉优服务共享平台”发布的商品中发生一笔退款，请及时登录平台处理，谢谢！");
        }catch (Exception e){

        }
    }

    @Override
    @Transactional
    public void dealRefund(Long orderItemId, SysUser user, Integer status) {
        Example<ServiceOrderItem> example=ServiceOrderItem.createExample();
        Example.Criteria criteria=example.createCriteria();
        if (user!=null){
            criteria.andEqualTo("sellerId",user.getUserId());
        }
        criteria.andEqualTo("orderItemId",orderItemId);
        ServiceOrderItem serviceOrderItem=this.findOneByExample(example);
        if (serviceOrderItem==null) {
            throw new BusException("查不到该订单信息，处理退款失败");
        }
        ServiceOrderItem serviceOrderItemVo=new ServiceOrderItem();
        serviceOrderItemVo.setOrderItemId(orderItemId);
        serviceOrderItemVo.setUpdateTime(TimeUtils.now());
        String productType=serviceOrderItem.getType()==2?"课室":"商品";
        String msg=null;
        if(status==0){//不同意，重新设为已付款状态
            serviceOrderItemVo.setChargingStatus(2);
            serviceOrderItemVo.setOrderStatus(serviceOrderItem.getGoodState());
            msg="您好，您在“誉优服务共享平台”发起的退款申请（"+productType+"名："+serviceOrderItem.getProductName()+"），卖家已拒绝退款，请及时登录平台查看并与卖家协商解决，谢谢！   ";
        }else if (status==1){
            serviceOrderItemVo.setChargingStatus(5);
            serviceOrderItemVo.setOrderStatus(5);
            serviceOrderItemVo.setRefundTime(TimeUtils.now());

            if (serviceOrderItem.getType()==2){
                /*租赁信息设置为失败*/
                personLeaseMessageService.changeLeaseStateByIds(Utils.toLongIds(serviceOrderItem.getPersonLeaseIds()),2);
            }
            if (serviceOrderItem.getPayWay()==3){
                String remark=(serviceOrderItem.getType()==2?"租赁":"商品")+"订单("+serviceOrderItem.getProductName()+")退款";
                //Long mainAccountId,Long feeCategoryId, Long relMainAccountId , Long incomeCategoryId , BigDecimal amount, String remark ,String tags , Long trackingId;
                settlementService.bookRefundForDeal(serviceOrderItem.getPaidAmount(),remark ,serviceOrderItem.getOrderItemId());
            }
            //msg="您好，您在“誉优服务共享平台”发起的退款申请（"+productType+"名："+serviceOrderItem.getProductName()+"），卖家已拒绝退款，请及时登录平台查看并与卖家协商解决，谢谢！   ";
            msg="您好，您在“誉优服务共享平台”发起的退款申请（"+productType+"名："+serviceOrderItem.getProductName()+"），已经退款成功，谢谢！";
        }
        try{
            smsService.send(Arrays.asList(serviceOrderItem.getBuyerPhoneNo()),msg);
        }catch (Exception e){

        }



        this.updateSelectiveById(serviceOrderItemVo);
    }

    @Override
    @Transactional
    public void payServiceOrderItem(Long orderItemId, BigDecimal paidAmount,Integer payWay) {
        ServiceOrderItem serviceOrderItem=this.findById(orderItemId);
        if (serviceOrderItem.getChargingStatus()==2) {
            if (payWay==3){
                throw new BusException("orderItemId为:"+orderItemId+"的订单已经支付");
            }else {
                return;
            }
        }
        BigDecimal temp=serviceOrderItem.getPayableAmount().subtract(serviceOrderItem.getPaidAmount());

        if (temp.doubleValue()<paidAmount.doubleValue()){
            throw new BusException("付款金额小于应付金额");
        }

        ServiceOrderItem serviceOrderItem1=new ServiceOrderItem();
        serviceOrderItem1.setOrderItemId(serviceOrderItem.getOrderItemId());
        serviceOrderItem1.setChargingStatus(2);
        serviceOrderItem1.setOrderStatus(2);
        serviceOrderItem1.setUpdateTime(TimeUtils.now());
        serviceOrderItem1.setPaidAmount(paidAmount);
        serviceOrderItem1.setPayWay(payWay);
        serviceOrderItem1.setPayTime(TimeUtils.now());
        this.updateSelectiveById(serviceOrderItem1);
        Long unFinishOrderItemNum=this.countUnFinishOrderItem(serviceOrderItem.getOrderId(),Arrays.asList(0));
        ServiceOrder serviceOrder= serviceOrderService.findById(serviceOrderItem.getOrderId());
        ServiceOrder serviceOrder1=new ServiceOrder();
        serviceOrder1.setOrderId(serviceOrder.getOrderId());
        serviceOrder1.setPaidAmount(serviceOrder.getPaidAmount().add(paidAmount));
        serviceOrder1.setUpdateTime(TimeUtils.now());
        if (unFinishOrderItemNum.intValue()==0){
            serviceOrder1.setChargingStatus(2);
        }else {
            serviceOrder1.setChargingStatus(1);
        }
        serviceOrderService.updateSelectiveById(serviceOrder1);
        if (serviceOrderItem.getType()==0){
            ServiceProduct serviceProduct=serviceProductService.findById(serviceOrderItem.getProductId());
            Integer amount=serviceOrderItem.getQuantity()+serviceProduct.getAmount();
            ServiceProduct newServiceProduct=new ServiceProduct();
            newServiceProduct.setProductId(serviceProduct.getProductId());
            newServiceProduct.setAmount(amount);
            newServiceProduct.setUpdateTime(TimeUtils.now());
            serviceProductService.updateSelectiveById(newServiceProduct);

        }


        String personLeaseIds=serviceOrderItem.getPersonLeaseIds();
        if (StringUtils.isNotEmpty(personLeaseIds)){
            personLeaseMessageService.changeLeaseStateByIds(Utils.toLongIds(personLeaseIds),1);
        }

        if (payWay==3){
            ServiceCategory serviceCategory=serviceCategoryService.findById(serviceOrderItem.getCategoryId());
            String remark=(serviceOrderItem.getType()==2?"租赁":"商品")+"订单("+serviceOrderItem.getProductName()+")购买";
            if (serviceOrderItem.getType()==2){
                settlementService.bookLeaseDeal(serviceOrderItem.getPayMainAccountId(),serviceOrderItem.getProfitMainAccountId(),serviceOrderItem.getPayableAmount(),remark,serviceOrderItem.getMinStartDate(),serviceOrderItem.getMaxEndDate(),serviceOrderItem.getOrderItemId());
            }else if(serviceOrderItem.getType()==0){
                settlementService.bookProductDeal(serviceOrderItem.getPayMainAccountId(),serviceCategory.getFeeCategoryId(),serviceOrderItem.getProfitMainAccountId(),serviceOrderItem.getPayableAmount(),remark,serviceOrderItem.getOrderItemId());
            }
        }


    }

    @Override
    public Page<ServiceOrderItem> findByQueryCond(ServiceOrderItemQueryVo serviceOrderItemQueryVo,Integer pageNo,Integer pageSize) {
        Example<ServiceOrderItem> example=ServiceOrderItem.createExample();
        Example.Criteria criteria=example.createCriteria();
        if (serviceOrderItemQueryVo.getSellerId()!=null){
            criteria.andEqualTo("sellerId",serviceOrderItemQueryVo.getSellerId());
        }
        if (serviceOrderItemQueryVo.getBuyerId()!=null){
            criteria.andEqualTo("buyerId",serviceOrderItemQueryVo.getBuyerId());
        }

        if (serviceOrderItemQueryVo.getOrderStatus()!=null){
            criteria.andEqualTo("orderStatus",serviceOrderItemQueryVo.getOrderStatus());
        }

        if (serviceOrderItemQueryVo.getChargingStatus()!=null){
            criteria.andEqualTo("chargingStatus",serviceOrderItemQueryVo.getChargingStatus());
        }


        if (serviceOrderItemQueryVo.getBeginPayTime()!=null){
            criteria.andGreaterThanOrEqualTo("payTime",TimeUtils.startOfDate(serviceOrderItemQueryVo.getBeginPayTime()));
        }
        if (serviceOrderItemQueryVo.getEndPayTime()!=null){
            criteria.andLessThanOrEqualTo("payTime",TimeUtils.endOfDate(serviceOrderItemQueryVo.getEndPayTime()));
        }
        if (serviceOrderItemQueryVo.getBeginRefundTime()!=null){
            criteria.andGreaterThanOrEqualTo("refundTime",TimeUtils.startOfDate(serviceOrderItemQueryVo.getBeginRefundTime()));
        }
        if (serviceOrderItemQueryVo.getEndRefundTime()!=null){
            criteria.andLessThanOrEqualTo("refundTime",TimeUtils.endOfDate(serviceOrderItemQueryVo.getEndRefundTime()));
        }






        if (serviceOrderItemQueryVo.getType()!=null){
            criteria.andEqualTo("type",serviceOrderItemQueryVo.getType());
        }
        if (StringUtils.isNotEmpty(serviceOrderItemQueryVo.getProductName())){
            criteria.andLike("productName","%"+serviceOrderItemQueryVo.getProductName()+"%");
        }
        if (serviceOrderItemQueryVo.getTimeType()!=null){
            Date date = new Date();
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            if(serviceOrderItemQueryVo.getTimeType() == 0) {
                cal.add(Calendar.DATE, -7);
            } else if(serviceOrderItemQueryVo.getTimeType() == 1) {
                cal.add(Calendar.MONTH, -1);
            } else if(serviceOrderItemQueryVo.getTimeType() == 2) {
                cal.add(Calendar.MONTH, -3);
            } else if(serviceOrderItemQueryVo.getTimeType() == 3) {
                cal.add(Calendar.YEAR, -1);
            }
            criteria.andGreaterThan("createTime",cal.getTime());
        }
        example.orderBy("updateTime").desc();
        Page<ServiceOrderItem> page=findPageByExample(example,pageNo,pageSize);

        List<ServiceOrderItem> serviceOrderItemList=page.getRecords();
        if (serviceOrderItemList!=null){
            List<Long> payMainAccountIds=BeanUtils.toList(serviceOrderItemList,"payMainAccountId");
            List<MainAccount> mainAccountList=mainAccountService.findByIds(payMainAccountIds,"mainAccountId","name");
            Map<Long,MainAccount> mainAccountMap=BeanUtils.toMap(mainAccountList,"mainAccountId");
            for (ServiceOrderItem serviceOrderItem:serviceOrderItemList){
                if (serviceOrderItem.getType()==2){
                    String personLeaseMessages=serviceOrderItem.getPersonLeaseIds();
                    if (StringUtils.isNotEmpty(personLeaseMessages)){
                        PersonLeaseQueryVo personLeaseQueryVo=new PersonLeaseQueryVo();
                        personLeaseQueryVo.setPersonLeaseIds(personLeaseMessages);
                        List<PersonLeaseMessage> personLeaseMessageList=personLeaseMessageService.findPersonLeaseMessage(personLeaseQueryVo);
                        serviceOrderItem.setPersonLeaseMessageList(personLeaseMessageList);
                        List<PersonLeaseMessage> confictList=new ArrayList<PersonLeaseMessage>();
                        for (PersonLeaseMessage personLeaseMessage:personLeaseMessageList){
                            String confictIds=personLeaseMessage.getConfictIds();
                            if (StringUtils.isNotEmpty(confictIds)){
                                List<PersonLeaseMessage> temp=personLeaseMessageService.findByIds(Utils.toLongIds(confictIds));
                                temp=personLeaseMessageService.changeTimeDesc(personLeaseMessage,temp);
                                confictList.addAll(temp);
                            }
                        }
                        if (mainAccountMap.containsKey(serviceOrderItem.getPayMainAccountId())){
                            serviceOrderItem.setPayMainAccountName(mainAccountMap.get(serviceOrderItem.getPayMainAccountId()).getName());
                        }
                        serviceOrderItem.setConflictList(confictList);
                    }
                }
            }
        }
        return page;
    }


    @Override
    public Page<ServiceOrderItemResultVo> fillByItemPage(Page<ServiceOrderItem> serviceOrderItemPage) {
        Page<ServiceOrderItemResultVo> serviceOrderItemResultVoPage=Utils.newPage(serviceOrderItemPage);
        List<ServiceOrderItem> serviceOrderItemList=serviceOrderItemPage.getRecords();
        if (serviceOrderItemList!=null && serviceOrderItemList.size()>0){
            List<Long> productIdList=BeanUtils.toList(serviceOrderItemList,"productId");
            List<ServiceProduct> serviceProductList=serviceProductService.findByIds(productIdList);
            List<ServiceOrderItemResultVo> serviceOrderItemResultVoList=new ArrayList<ServiceOrderItemResultVo>(serviceOrderItemList.size());
            for (ServiceOrderItem serviceOrderItem:serviceOrderItemList){
                ServiceOrderItemResultVo serviceOrderItemVo=new ServiceOrderItemResultVo();
                BeanUtils.copyProperties(serviceOrderItemVo,serviceOrderItem);
                for (ServiceProduct serviceProduct:serviceProductList){
                    if (serviceOrderItem.getProductId().equals(serviceProduct.getProductId())){
                        serviceOrderItemVo.setStatus(serviceProduct.getStatus());
                    }
                }
                serviceOrderItemResultVoList.add(serviceOrderItemVo);

            }
            serviceOrderItemResultVoPage.setRecords(serviceOrderItemResultVoList);

        }
        return serviceOrderItemResultVoPage;
    }

    @Override
    public ServiceOrderItem findByItemId(Long orderItemId) {
        ServiceOrderItem serviceOrderItem=this.findById(orderItemId);
        if (serviceOrderItem==null) {
            throw  new BusException("该订单不存在");
        }
        if (serviceOrderItem.getType()==2){
            String personLeaseMessages=serviceOrderItem.getPersonLeaseIds();
            if (StringUtils.isNotEmpty(personLeaseMessages)){
                PersonLeaseQueryVo personLeaseQueryVo=new PersonLeaseQueryVo();
                personLeaseQueryVo.setPersonLeaseIds(personLeaseMessages);
                List<PersonLeaseMessage> personLeaseMessageList=personLeaseMessageService.findPersonLeaseMessage(personLeaseQueryVo);
                serviceOrderItem.setPersonLeaseMessageList(personLeaseMessageList);
                List<PersonLeaseMessage> confictList=new ArrayList<PersonLeaseMessage>();
                for (PersonLeaseMessage personLeaseMessage:personLeaseMessageList){
                    String confictIds=personLeaseMessage.getConfictIds();
                    if (StringUtils.isNotEmpty(confictIds)){
                        List<PersonLeaseMessage> temp=personLeaseMessageService.findByIds(Utils.toLongIds(confictIds));
                        temp=personLeaseMessageService.changeTimeDesc(personLeaseMessage,temp);
                        confictList.addAll(temp);
                    }
                }
                serviceOrderItem.setConflictList(confictList);
            }
        }
        return serviceOrderItem;
    }

    @Override
    public Long countUnFinishOrderItem(Long orderId, List<Integer> chargingStatusList) {
        Example<ServiceOrderItem> example=ServiceOrderItem.createExample();
        Example.Criteria criteria=example.createCriteria();
        criteria.andEqualTo("orderId",orderId);
        criteria.andIn("chargingStatus",chargingStatusList);
        return countByExample(example);
    }

    @Override
    public ServiceOrderItem changeStatusById(Long serviceOrderItemId, Integer status) {
        ServiceOrderItem serviceOrderItem=new ServiceOrderItem();
        serviceOrderItem.setOrderItemId(serviceOrderItemId);
        serviceOrderItem.setChargingStatus(status);
        updateSelectiveById(serviceOrderItem);
        return serviceOrderItem;
    }

    @Override
    public ServiceOrderItem changeGoodStateById(Long serviceOrderItemId, Integer goodState) {
        ServiceOrderItem serviceOrderItem=new ServiceOrderItem();
        serviceOrderItem.setOrderItemId(serviceOrderItemId);
        serviceOrderItem.setGoodState(goodState);
        serviceOrderItem.setOrderStatus(goodState);
        serviceOrderItem.setUpdateTime(TimeUtils.now());
        updateSelectiveById(serviceOrderItem);
        return serviceOrderItem;
    }

    @Override
    public ServiceOrderItem changeIsCommentsById(Long serviceOrderItemId, Integer isComments) {
        ServiceOrderItem serviceOrderItem=new ServiceOrderItem();
        serviceOrderItem.setOrderItemId(serviceOrderItemId);
        serviceOrderItem.setIsComments(isComments);
        updateSelectiveById(serviceOrderItem);
        return serviceOrderItem;
    }





    @Override
    public List<ServiceOrderItem> findOrderItemListByOrderId(Long orderId) {
        Example<ServiceOrderItem> example = ServiceOrderItem.createExample();
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderId" , orderId );
        return findListByExample(example);
    }

    @Override
    public ServiceOrderItemVo findOrderItemDetailById(Long orderItemId) {
        ServiceOrderItemVo vo = new ServiceOrderItemVo();
        ServiceOrderItem item = findById(orderItemId);
        vo.setOrder(orderService.findById(item.getOrderId()));
        BeanUtils.copyProperties(vo,item);
        return vo;
    }

    @Override
    public void changeOrderItemStatus(Long orderItemId,Integer status) {
        ServiceOrderItem item =findById(orderItemId);
        item.setChargingStatus(status);
        updateSelectiveById(item);
        if(status==1){
            orderService.changOrderStatus(item.getOrderId(),1);
        }
    }

    @Override
    public void orderItemStatus(Long orderId) {
        List<ServiceOrderItem> orderItemList = this.findOrderItemListByOrderId(orderId);
        for (ServiceOrderItem orderItem : orderItemList) {
            orderItem.setChargingStatus(1);
            this.updateSelectiveById(orderItem);
        }
    }

    @Override
    public void sendGoods(Long orderId) {
        List<ServiceOrderItem> orderItemList = this.findOrderItemListByOrderId(orderId);
        for (ServiceOrderItem orderItem : orderItemList) {
            orderItem.setChargingStatus(2);
            this.updateSelectiveById(orderItem);
        }
    }

    @Override
    public void tradeSuccess(Long orderId) {
        List<ServiceOrderItem> orderItemList = this.findOrderItemListByOrderId(orderId);
        for (ServiceOrderItem orderItem : orderItemList) {
            orderItem.setChargingStatus(3);
            this.updateSelectiveById(orderItem);
        }
    }

    @Override
    public List<Long> findRoomIds(Long busTeamId) {
        Example<ServiceOrderItem> example = ServiceOrderItem.createExample();
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("busTeamId",busTeamId);
        //交易成功
        criteria.andEqualTo("status",3);
        List<ServiceOrderItem> serviceOrderItemList= findListByExample(example);
        Set<Long> roomIds = new HashSet<>();
        for (ServiceOrderItem item : serviceOrderItemList) {
            roomIds.add(item.getProductId());
        }
        return new ArrayList<>(roomIds);
    }


    @Override
    public void changeOrderItemStatusByIds(List<Long> orderItemIds, Integer status) {
        Example<ServiceOrderItem> example=ServiceOrderItem.createExample();
        example.createCriteria().andIn("orderItemId",orderItemIds);
        ServiceOrderItem serviceOrderItem=new ServiceOrderItem();
        serviceOrderItem.setChargingStatus(status);
        this.updateSelectiveByExample(serviceOrderItem,example);
    }

    @Override
    @Transactional
    public void changeStatusByServiceOrder(ServiceOrder serviceOrder) {
   /*     List<ServiceOrderItem> serviceOrderItemList=this.findOrderItemListByOrderId(serviceOrder.getOrderId());
        List<Long>  orderItemIdList=BeanUtils.toList(serviceOrderItemList,"orderItemId");
        this.changeOrderItemStatusByIds(orderItemIdList,serviceOrder.getChargingStatus());
        List<String> personLeaseIdsList=BeanUtils.toList(serviceOrderItemList,"personLeaseId");
        if (serviceOrder.getType()==2){//租赁单更改租赁时间状态。
            for (String personLeaseIds:personLeaseIdsList){
                String[] personLeaseIdArr=personLeaseIds.split(",");
                List<Long> personLeaseIdList=new ArrayList<Long>(personLeaseIdArr.length);
                for (String personLeaseId:personLeaseIdArr){
                    personLeaseIdList.add(Long.parseLong(personLeaseId));
                    personLeaseMessageService.changeLeaseStateByIds(personLeaseIdList,serviceOrder.getChargingStatus());
                }
            }
        }*/
    }

    @Override
    public List<ServiceOrderItem> findByProductIdAndStatusList(Long productId, List<Integer> statusList) {
        Example<ServiceOrderItem> example=ServiceOrderItem.createExample();
        example.createCriteria().andEqualTo("productId",productId).andIn("status",statusList);

        return this.findListByExample(example);
    }

    @Override
    public Long countOrderNumByUserId(Long userId) {
        Example<ServiceOrderItem> example=ServiceOrderItem.createExample();
        Example.Criteria criteria=example.createCriteria();
        criteria.andEqualTo("buyerId",userId);
        return countByExample(example);
    }

    @Override
    public Long countOrderNumByOrderId(Long orderId) {
        Example<ServiceOrderItem> example=ServiceOrderItem.createExample();
        Example.Criteria criteria=example.createCriteria();
        criteria.andEqualTo("order",orderId);
        return countByExample(example);
    }

    @Override
    public BigDecimal countLeaseOneDayByOrderItemId(Long orderItemId, Date date) {
        ServiceOrderItem serviceOrderItem=this.findById(orderItemId);
        date=Utils.parseDate(Utils.formatDate(date,"yyyy-MM-dd"),"yyyy-MM-dd");
        BigDecimal result=BigDecimal.ZERO;
        if (serviceOrderItem.getChargingStatus()!=2){
            return result;
        }
        String personLeaseIds=serviceOrderItem.getPersonLeaseIds();
        if (StringUtils.isNotEmpty(personLeaseIds)){
            List<Long> personLeaseIdList=Utils.toLongIds(personLeaseIds);
            List<PersonLeaseMessage> personLeaseMessageList=personLeaseMessageService.findByIdsAndDate(personLeaseIdList,date);
            for (PersonLeaseMessage personLeaseMessage:personLeaseMessageList){
                if (personLeaseMessage.getWeekNum()!=null && personLeaseMessage.getWeekNum()!=-1 && personLeaseMessage.getWeekNum()!=TimeUtils.getWeekOfDate(date)){
                    continue;
                }
                String timePrice=personLeaseMessage.getTimePrice();
                TimePriceVo timePriceVo=JSONObject.parseObject(timePrice,TimePriceVo.class);
                List<SummerWinterDate> summerWinterDateList=timePriceVo.getSummerWinterDateList();
                List<LeasePriceVo> leasePriceVoList=timePriceVo.getLeasePriceVoList();
                Map<String, SummerWinterDate> summerWinterDateMap = BeanUtils.toMap(summerWinterDateList, "year");
                String year = Utils.formatDate(date, "yyyy");
                SummerWinterDate summerWinterDate = summerWinterDateMap.get(year);
                if (personLeaseMessage.getTimeType()==-1){
                    Integer hour = Integer.parseInt(personLeaseMessage.getEndTime().split(":")[0]) - Integer.parseInt(personLeaseMessage.getStartTime().split(":")[0]);
                    for (LeasePriceVo leasePriceVo:leasePriceVoList){
                        if (leasePriceVo.getsWHourPrice() != null && summerWinterDate != null && ((date.getTime() >= summerWinterDate.getWinterStartDate().getTime() && date.getTime() <= summerWinterDate.getWinterEndDate().getTime())
                                || (date.getTime() >= summerWinterDate.getSummerStartDate().getTime() && date.getTime()<=summerWinterDate.getSummerEndDate().getTime()))
                                ){
                            result=result.add(leasePriceVo.getsWHourPrice().multiply(new BigDecimal(hour)));
                            break;
                        } else if (leasePriceVo.getWeekendHourPrice()!=null && leasePriceVo.getStart().getTime()<=date.getTime() && leasePriceVo.getEnd().getTime()>=date.getTime() && (TimeUtils.getWeekOfDate(date) == 6 || TimeUtils.getWeekOfDate(date) == 0)) {
                            result=result.add(leasePriceVo.getWeekendHourPrice().multiply(new BigDecimal(hour)));
                            break;
                        } else if (leasePriceVo.getWorkingHourPrice()!=null && leasePriceVo.getStart().getTime()<=date.getTime() && leasePriceVo.getEnd().getTime()>=date.getTime() ){
                            result=result.add(leasePriceVo.getWorkingHourPrice().multiply(new BigDecimal(hour)));
                            break;
                        }
                    }
                }else if (personLeaseMessage.getTimeType()!=null && personLeaseMessage.getWeekNum()!=null && personLeaseMessage.getWeekNum()!=-1){
                    for (LeasePriceVo leasePriceVo:leasePriceVoList){
                        if (leasePriceVo.getsWDayPrice() != null && summerWinterDate != null && ((date.getTime() >= summerWinterDate.getWinterStartDate().getTime() && date.getTime() <= summerWinterDate.getWinterEndDate().getTime())
                                || (date.getTime() >= summerWinterDate.getSummerStartDate().getTime() && date.getTime()<=summerWinterDate.getSummerEndDate().getTime()))
                                ){
                            result=result.add(leasePriceVo.getsWDayPrice());
                            break;
                        } else if (leasePriceVo.getWeekendDayPrice()!=null && leasePriceVo.getStart().getTime()<=date.getTime() && leasePriceVo.getEnd().getTime()>=date.getTime() && (TimeUtils.getWeekOfDate(date) == 6 || TimeUtils.getWeekOfDate(date) == 0)) {
                            result=result.add(leasePriceVo.getWeekendDayPrice());
                            break;
                        } else if (leasePriceVo.getWorkingDayPrice()!=null &&leasePriceVo.getStart().getTime()<=date.getTime() && leasePriceVo.getEnd().getTime()>=date.getTime() ){
                            result=result.add(leasePriceVo.getWorkingDayPrice());
                            break;
                        }
                    }
                }else {
                    for (LeasePriceVo leasePriceVo:leasePriceVoList){
                        if (leasePriceVo.getStart().getTime()<=date.getTime() && leasePriceVo.getEnd().getTime()>=date.getTime()){
                            Date startDate=personLeaseMessage.getStart().getTime()<leasePriceVo.getStart().getTime()?leasePriceVo.getStart():personLeaseMessage.getStart();
                            Date endDate=personLeaseMessage.getEnd().getTime()>leasePriceVo.getEnd().getTime()?leasePriceVo.getEnd():personLeaseMessage.getEnd();
                            Boolean hasCount=false;
                            while (TimeUtils.changeDateByNum(TimeUtils.addYearByNum(startDate,1),-1).getTime()<=endDate.getTime()){
                                startDate=TimeUtils.addYearByNum(startDate,1);
                                if (leasePriceVo.getYearPrice()!=null && date.getTime()<=startDate.getTime()){
                                    Integer yearNum=TimeUtils.daysOfTwo(TimeUtils.addYearByNum(startDate,-1),startDate);
                                    result=result.add(leasePriceVo.getYearPrice().divide(new BigDecimal(yearNum),10,BigDecimal.ROUND_HALF_UP));
                                    hasCount=true;
                                    break;
                                }
                            }
                            if (hasCount){
                                break;
                            }
                            while (TimeUtils.changeDateByNum(TimeUtils.addMonthByNum(startDate,1),-1).getTime()<=endDate.getTime()){
                                startDate=TimeUtils.addMonthByNum(startDate,1);
                                if (leasePriceVo.getMonthPrice()!=null&&date.getTime()<=startDate.getTime()){
                                    Integer monthNum=TimeUtils.daysOfTwo(TimeUtils.addMonthByNum(startDate,-1),startDate);
                                    result=result.add(leasePriceVo.getMonthPrice().divide(new BigDecimal(monthNum),10,BigDecimal.ROUND_HALF_UP));
                                    hasCount=true;
                                    break;
                                }
                            }
                            if (hasCount){
                                break;
                            }
                            if (leasePriceVo.getsWDayPrice() != null && summerWinterDate != null && ((date.getTime() >= summerWinterDate.getWinterStartDate().getTime() && date.getTime() <= summerWinterDate.getWinterEndDate().getTime())
                                    || (date.getTime() >= summerWinterDate.getSummerStartDate().getTime() && date.getTime()<=summerWinterDate.getSummerEndDate().getTime()))
                                    ){
                                result=result.add(leasePriceVo.getsWDayPrice());
                                break;
                            } else if (leasePriceVo.getWeekendDayPrice()!=null && leasePriceVo.getStart().getTime()<=date.getTime() && leasePriceVo.getEnd().getTime()>=date.getTime() && (TimeUtils.getWeekOfDate(date) == 6 || TimeUtils.getWeekOfDate(date) == 0)) {
                                result=result.add(leasePriceVo.getWeekendDayPrice());
                                break;
                            } else if (leasePriceVo.getWorkingDayPrice()!=null &&leasePriceVo.getStart().getTime()<=date.getTime() && leasePriceVo.getEnd().getTime()>=date.getTime() ){
                                result=result.add(leasePriceVo.getWorkingDayPrice());
                                break;
                            }
                        }
                    }
                }
            }
        }
        return result;
    }
}